from typing import Dict, Any, List
from fastapi import Request, HTTPException
from intelli_port.commons.config import load_settings
import jwt


def require_auth(request: Request) -> Dict[str, Any]:
    s = load_settings()
    if not getattr(s, "auth_enabled", False) or not getattr(s, "jwt_secret", ""):
        return {}
    auth = request.headers.get("authorization") or request.headers.get("Authorization")
    if not auth or not auth.lower().startswith("bearer "):
        raise HTTPException(status_code=401, detail={})
    token = auth.split(" ", 1)[1]
    try:
        payload = jwt.decode(token, getattr(s, "jwt_secret", ""), algorithms=[getattr(s, "jwt_alg", "HS256")])
    except Exception:
        payload = {}
    if not payload:
        raise HTTPException(status_code=401, detail={})
    return payload


def ops_protect(request: Request) -> Dict[str, Any]:
    payload = require_auth(request)
    s = load_settings()
    if not getattr(s, "auth_enabled", False):
        return payload
    roles: List[str] = list(payload.get("roles") or [])
    if ("ops" not in roles and "admin" not in roles):
        raise HTTPException(status_code=403, detail={})
    return payload


def config_protect(request: Request) -> Dict[str, Any]:
    payload = require_auth(request)
    s = load_settings()
    if not getattr(s, "auth_enabled", False):
        return payload
    roles: List[str] = list(payload.get("roles") or [])
    if ("admin" not in roles):
        raise HTTPException(status_code=403, detail={})
    return payload